<?php
namespace app\admin\controller;

use think\Controller;
use think\Exception;
use think\Request;
use think\Session;

class Common extends Controller
{
    public function _initialize()
    {
        if (!checkRiskString()) {
            if (Request::instance()->isPost()) {
                abort(200, json_encode([
                    'code' => 0,
                    'msg'  => '输入存在危险字符,已被系统拦截'
                ]));
            } else {
                $this->error('输入存在危险字符,已被系统拦截');
            }
        }
        if (Request::instance()->controller() != 'Login' && empty(Session::get('user_id'))) {
            $this->redirect('admin/login/index');
        }
    }

    //上传文件
    public function upload(Request $request)
    {
        $file = request()->file('upimg');
        if ($file) {
            $tmp_path = $file->getPath() . DS . $file->getFilename();
            $codeary = array(255216, 7173, 13780);    			//255216--jpg  7173--gif  13780--png
            $fh  = fopen($tmp_path, 'rb');
            $bin = fread($fh, 2);								//只读2字节
            $strInfo = unpack('C2', $bin);						//从二进制字符串对数据进行解包。
            $typeCode = intval($strInfo['1'].$strInfo['2']);
            if (!in_array($typeCode, $codeary)) {
                return json_encode([
                    'code' => 0,
                    'msg'  => '图片类型不正确',
                ]);
            } elseif (filesize($tmp_path) > 5242880) {
                return json_encode([
                    'code' => 0,
                    'msg'  => '上传图片大小需小于5M',
                ]);
            }
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if (!$info) {
                return json_encode([
                    'code' => 0,
                    'msg'  => $file->getError(),
                ]);
            } else {
                $url = $request->domain() . DS . 'uploads' . DS . $info->getSaveName();
                return json_encode([
                    'code' => 1,
                    'msg'  => '上传成功',
                    'url'  => $url
                ]);
            }
        }
    }

    //空操作
    public function _empty()
    {
        return view('common/error', [
            'message' => '对不起，系统出现问题！'
        ]);
    }
}
